package com.hetwen.remoteboot.activity;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

import com.hetwen.remoteboot.R;
import com.hetwen.remoteboot.dao.MacAddrDao;
import com.hetwen.remoteboot.model.MacAddr;
import com.hetwen.remoteboot.packet.PacketSender;

@SuppressWarnings("deprecation")
public class MainActivity extends ActionBarActivity {

	private static final String AUTHORITY = "com.hetwen.remoteboot";
	
	private Context context;
	private ListView lv_addrs;
	private List<MacAddr> addrs;
	private MacAddrAdapter adapter;
	private MacAddrDao dao;

	private List<MacAddr> bootList;

	private ContentResolver resolver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		initView();
		initData();
	}

	/**
	 * 初始化View
	 */
	private void initView() {
		setShowOverflow();
		lv_addrs = (ListView) findViewById(R.id.activity_main_lv_addr);
	}

	/**
	 * 初始化Data
	 */
	private void initData() {
		bootList = new ArrayList<MacAddr>();
		dao = new MacAddrDao(context);
		testQuery();
	}

	@Override
	protected void onResume() {
		super.onResume();
		addrs = dao.queryAll();
		if(adapter == null){
			adapter = new MacAddrAdapter(addrs);
			lv_addrs.setAdapter(adapter);
		}else{
			adapter.refresh(addrs);
		}
	}

	/**
	 * 开机
	 * 
	 * @param v
	 */
	public void boot(View v) {
		PacketSender sender = new PacketSender(context);
		sender.send(bootList);
	}

	/**
	 * Adapter
	 */
	private class MacAddrAdapter extends BaseAdapter {

		private List<MacAddr> list;

		public MacAddrAdapter(List<MacAddr> list) {
			this.list = list;
		}

		public void refresh(List<MacAddr> list){
			this.list = list;
			this.notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			
			if (convertView == null) {
				convertView = View.inflate(context,
						R.layout.activity_main_listview_addr_item, null);
				TextView tv_name = (TextView) convertView
						.findViewById(R.id.tv_addr_name);
				TextView tv_mac = (TextView) convertView
						.findViewById(R.id.tv_addr_mac);
				CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb_addr);

				holder = new ViewHolder();
				holder.tv_addr_name = tv_name;
				holder.tv_addr_mac = tv_mac;
				holder.cb_addr = cb;

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final MacAddr macAddr = list.get(position);
			holder.tv_addr_name.setText(macAddr.name);
			holder.tv_addr_mac.setText(macAddr.mac);
			holder.cb_addr
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							if (isChecked) {
								if (bootList.contains(macAddr)) {
								} else {
									bootList.add(macAddr);
								}
							} else {
								if (bootList.contains(macAddr)) {
									bootList.remove(macAddr);
								} else {
								}
							}
						}
					});
			return convertView;
		}
	}

	private class ViewHolder {
		TextView tv_addr_name;
		TextView tv_addr_mac;
		CheckBox cb_addr;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			startActivity(new Intent(this, SettingsActivity.class));
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				try {
					Method m = menu.getClass().getDeclaredMethod(
							"setOptionalIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}

	/**
	 * showOverFlow
	 */
	protected void setShowOverflow() {
		try {
			ViewConfiguration viewConfig = ViewConfiguration.get(this);
			Field field = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			field.setAccessible(true);
			field.setBoolean(viewConfig, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void testQuery(){
		Uri uri = Uri.parse("content://"+AUTHORITY+"/"+"mac_addresses");
		resolver = getContentResolver();
		Cursor cursor = resolver.query(uri, null, null, null, null);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				int id = cursor.getInt(0);
				String name = cursor.getString(1);
				String mac = cursor.getString(2);
				MacAddr addr = new MacAddr(id, name, mac);
				System.out.println(addr.toString());
			}
			cursor.close();
		}
	}
}
